import java.awt.*;
import java.awt.event.*;
import java.util.*;

/*
  @author Rene Thomsen
  @version 1.0
*/
public class GridWorld extends Frame {
    
    private Graphics g;
        
    /* transform coordinates, so that we write pixels below the windowbar */
    private int diff = 20;

    private TwoDimSim model;
    
    private int zoom;
    private int scale = 5; 
    private int dimension = 300;
    
    private Graphics bufferGfx;
    private Image buffer;

    /* toggle view between traced moves and actural moves */
    private int trace;
    
    public GridWorld(String title, 
		     TwoDimSim model,
		     int zoom,
		     int trace) {
	super(title);
	this.model = model;
	this.dimension = model.population.length;
	this.trace = trace;
	this.zoom = zoom;
	if (zoom != 1) scale = 1;
	init();
    }

    private void init() {
	setSize(scale*dimension,scale*dimension+diff);
	setLocation(50,50);
	setBackground(Color.black);
	setResizable(false);
	setVisible(true);
	setLayout(new FlowLayout());
	addWindowListener(new WindowAdapter() {
		public void windowClosing(WindowEvent e) {
		    dispose();
		}
	    });
    }
    
    public void paint(Graphics g) {
	update(g);
    }
    
    //kaldes fra TwoDimSim
    public void update() {
	if (bufferGfx == null) {
	    buffer = createImage(scale*dimension,scale*dimension+diff);
	    bufferGfx = buffer.getGraphics();
	}
	drawFrame();
	update(getGraphics());
    }

    public void update(Graphics g) {
	if (bufferGfx == null) {
	    buffer = createImage(scale*dimension,scale*dimension+diff);
	    bufferGfx = buffer.getGraphics();
	}
	g.drawImage(buffer,0,0,this);
    }
    
    private void drawFrame() {
	if (trace != 1) 
	    /* clear previous view */
	    bufferGfx.clearRect(0,diff,scale*dimension,scale*dimension);
	
	for (int i=0; i<model.population.length; i++) {
	    for (int j=0; j<model.population.length; j++){
		CellIndividual individual = model.population[i][j];
		if (individual == null) 
		    bufferGfx.setColor(Color.black);
		else {	
		    int celltype = individual.getCelltype();
		    if (celltype == 0)
			bufferGfx.setColor(Color.white);
		    else if (celltype == 1)
			bufferGfx.setColor(Color.red);
		}
		
		if (zoom == 1)
		    bufferGfx.fillRect(scale*i,scale*j+diff,scale,scale);
		else 
		    bufferGfx.drawLine(i,j+diff,i,j+diff);
	    }
	}
    }//drawFrame
  
}

